/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="task-detail">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ name: 'home' }"><i class="el-icon-s-home"></i></el-breadcrumb-item>
            <el-breadcrumb-item style="cursor: pointer" @click.native="goBack">
                <lang>{{ upTitle }}</lang>
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                <lang>任务详情</lang>
            </el-breadcrumb-item>
        </el-breadcrumb>
        <div class="base_info base-card">
            <div class="base_info__title">
                <span class="info-title__left">
                    <span class="title-left__name"> {{ data.jobName }} </span>
                    <span :class="['table-status__'+data.jobStatus,'table-status__point']">{{ STATUS_MAP[data.jobStatus]
                        }}</span>
                </span>
                <span class="info-title__right">
                    <sf-button-primary v-if="data.jobStatus==='running'|| data.jobStatus==='queue' " @click="_killTask">
                        <lang>终止</lang>
                    </sf-button-primary>
                    <sf-button-primary v-else @click="_cloneTask">
                        <lang>克隆</lang>
                    </sf-button-primary>
                    <sf-button style="margin-left:16px ;" @click="getDetail">
                        <lang>刷新</lang>
                    </sf-button>
                </span>
            </div>
            <el-descriptions title="用户信息" :column="4" class="base-card__descriptions">
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="任务ID">{{ data.id }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="任务类型">{{ JOB_TYPE_MAP[data.jobType] }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="执行方式">{{ data.scheduleTime === '0' ? _('立即执行') : '-' }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="提交人">{{ data.ownerName }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="创建时间">{{ data.createTime }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="结束时间">{{ data.endTime ? data.endTime : '-' }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="运行时长">{{ data.executeTime | secToTime }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <div class="task_config base-card">
            <el-descriptions title="任务配置" class="base-card__descriptions">
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="资源配置">{{ data.resourceConfig }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="执行环境">{{ data.executeEnvironment }}
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="SQL执行脚本">
                    <el-link :underline="false" type="primary" @click="openSQLModal">
                        <lang>查看SQL执行脚本</lang>
                    </el-link>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="输入数据集">
                    <div style="max-height: 120px;overflow: auto;">
                        <div v-for="item in data.inputDataset" :key="item">
                            {{ item }}
                        </div>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item label-class-name="descriptions-label" content-class-name="descriptions-content"
                                      label="输出数据集">{{ data.outputDataspace + '/' + data.outputDataset }}
                </el-descriptions-item>
            </el-descriptions>
            <el-dialog :title=" _('查看SQL执行脚本')" append-to-body :visible.sync="sqlModalVisible">
                <sql-editor style="height: 600px;" :value="data.sqlText" :read-only="true"></sql-editor>
            </el-dialog>
        </div>
        <div class="execution_record base-card">
            <div class="execution_record__title">
                <lang>执行记录</lang>
            </div>
            <template v-if="data.jobStatus !== 'queue'">
                <sf-table ref="table"
                          default-height="calc(100% - 77px)"
                          :options="tableOption">
                    <sf-table-column
                        data-index="jobName"
                        :title="_('任务名称')"
                        :default-width="100">
                        <lang>任务名称</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="createTime"
                        :default-width="100">
                        <lang>创建时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="startTime"
                        :default-width="100">
                        <lang>开始时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="endTime"
                        :default-width="100">
                        <lang>结束时间</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="executeTime"
                        :default-width="100">
                        <lang>运行时长</lang>
                    </sf-table-column>
                    <template slot="executeTime"
                              slot-scope="{value}">
                        {{ value | secToTime }}
                    </template>
                    <sf-table-column
                        data-index="retryNo"
                        :default-width="100">
                        <lang>重试次数</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="jobStatus"
                        :default-width="100">
                        <lang>状态</lang>
                    </sf-table-column>
                    <template slot="jobStatus"
                              slot-scope="{value}">
          <span :class="['table-status__'+value,'table-status__point']">
              {{ STATUS_MAP[value] }}</span>
                    </template>
                    <sf-table-column
                        data-index="opr"
                        :default-width="100">
                        <lang>操作</lang>
                    </sf-table-column>
                    <!--额外操作-->
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a class="link-btn"
                               :class="{'disabled':record.jobStatus === 'queue'}"
                               @click="showLog(record)">
                                <lang>查看日志</lang>
                            </a>
                            <a class="link-btn"
                               :class="{'disabled':record.jobStatus!=='running'}"
                               style="border-left: 1px solid #D8D8D8; padding-left: 9px;"
                               @click="showTrend(record)">
                                <lang>查看趋势图</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </template>
            <template v-else>
                <el-empty>
                    <i slot="image" class="sf-comp-iconfont icon-comp-empty-status"></i>
                    <span slot="description">{{ _('当前任务正在排队中，暂无任务执行记录') }}</span>
                </el-empty>
            </template>
            <sf-drawer ref="drawer"
                       :size="1265"
                       :visible.sync="logDrawerVisible"
                       :destroy-on-close="true"
                       direction="rtl">
                <div slot="title">
                    <lang>查看日志</lang>
                </div>
                <log :data="logData" @close-logs="closeLogs"></log>
                <div slot="footer" style="display: flex;justify-content: flex-end">
                    <sf-button @click="closeLogs">
                        <lang>关闭</lang>
                    </sf-button>
                </div>
            </sf-drawer>
        </div>
    </div>
</template>

<script>
import {RUNNING_STATUS_MAP, HISTORY_STATUS_MAP, JOB_TYPE_MAP} from "../task_management/task_list/const";
import {secToTime} from 'src/util/time'
import SqlEditor from "../task_management/task_post/data_project/commen/sql_editor";
import Log from "./log";

const JOBS_LIST = {
    kill: `/task-manage/api/v1/jobs/kill`
};
const TASKDETAIL = '/task-manage/api/v1/jobs'
export default {
    name: "TaskDetail",
    filters: {
        secToTime,
    },
    components: {
        Log,
        SqlEditor
    },
    data() {
        return {
            logData: {},
            data: {},
            sqlModalVisible: false,
            logDrawerVisible: false,
            tableOption: {
                selectionHide: true,
            }
        }
    },
    mounted() {
        this.getDetail();
    },
    computed: {
        upTitle() {
            return this.$route.meta.upTitle;
        },
        tableData() {
            return this.data.executeHistory || [];
        },
        jobId() {
            return this.$route.query.jobId
        },
        STATUS_MAP() {
            return {
                ...RUNNING_STATUS_MAP, ...HISTORY_STATUS_MAP
            }
        },
        JOB_TYPE_MAP() {
            return JOB_TYPE_MAP
        }
    },
    methods: {
        goBack(){
            this.$router.go(-1)
        },
        closeLogs() {
            this.logDrawerVisible = false;
            this.$refs.drawer.closeDrawer();
        },
        async getDetail() {
            this.$mask()
            let {success, data, msg} = await this.$ajax.get(`${TASKDETAIL}/${this.jobId}`);
            this.$unmask()
            if (!success) {
                this.$warn(msg, {autoHide: true})
                this.$router.go(-1)
                return;
            }
            this.data = data;
            if (data.jobStatus !== 'queue') {
                this.$refs.table?.loadData(data.executeHistory)
            }
            this.$refs.drawer.closeDrawer() // 初始化的时候抽屉会加载一次 并不销毁，需要手动销毁一次
        },
        
        _cloneTask() {
            this.$store.commit('changeForm', {
                jobName: this.data.jobName,
                sqlText: this.data.sqlText,
                outputDataspace: this.data.outputDataspace,
                outputDataset: this.data.outputDataset,
                writeMode: this.data.writeMode,
                scheduleMod: this.data.scheduleMod,
                scheduleTim: this.data.scheduleTim
            })
            this.$store.commit('changeStep', 0);
            this.$router.push({name: 'data_project'})
        },
        
        _killTask() {
            let item = this.data;
            let params = {};
            let title = '';
            if (item) {
                params.id = item.id;
                title = item.jobName;
            }
            
            this.$confirm({
                title: _('任务终止'),
                subTitle: _('确定要终止“{0}”任务吗？', title),
                msg: item.jobStatus === 'running' ?
                    _('任务正在进行，终止任务将会使运行进度丢失') : _('排队任务终止后可在历史任务中重新提交'),
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxKillTask(params);
                    }
                }
            });
        },
        
        async ajaxKillTask(params) {
            this.$mask();
            let jsonData = await this.$ajax.post(`${JOBS_LIST.kill}/${params.id}`, params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('终止失败'));
            }
            this.$ok(_('终止成功'));
            
            this.getDetail();
        },
        
        openSQLModal() {
            this.sqlModalVisible = true;
        },
        async showLog(record) {
            this.logData = record
            this.logDrawerVisible = true
        },
        showTrend(record) {
            window.open(record.monitorUrl)
        }
    }
    
}
</script>

<style scoped lang="less">
.task-detail {
    overflow: auto;
    width: 100%;
    height: 100%;
    background-color: #f5f7fe;
    padding: 24px;
    
    .base-card {
        margin-top: 24px;
        padding: 32px 32px 0 24px;
        width: 100%;
        background-color: #ffffff;
        
        &__descriptions {
            width: 80%;
            
            /deep/ .descriptions-label {
                line-height: 22px;
                color: #86909C;
            }
            
            /deep/ .descriptions-content {
                line-height: 22px;
                color: #1D2129;
            }
        }
    }
    
    
    .el-breadcrumb {
        margin-bottom: 24px;
        
        .el-breadcrumb__item {
            /deep/ .is-link {
                font-weight: normal !important;
            }
            
            /deep/ .el-breadcrumb__inner {
                font-weight: 600;
            }
        }
    }
    
    .base_info {
        height: 256px;
        
        .base-card__descriptions {
            margin-top: 40px;
        }
        
        .base_info__title {
            display: flex;
            justify-content: space-between;
            
            .info-title__left {
                display: flex;
                align-items: center;
                
                .title-left__name {
                    font-size: 18px;
                    font-weight: bold;
                    line-height: 24px;
                    color: #3D3D3D;
                }
                
                .table-status__point {
                    margin-left: 24px;
                }
            }
        }
        
        
    }
    
    .task_config {
        height: 240px;
    }
    
    .execution_record {
        height: 266px;
        padding-top: 24px;
        
        &__title {
            font-size: 16px;
            font-weight: 700;
            color: #1D2129;
            margin-bottom: 24px;
        }
        
        .sfv-table {
            flex: 1;
            
            /deep/ .sfv-table_cell-center {
                text-align: center !important;
            }
            
            /deep/ .sfv-table_cell-left {
                text-align: left !important;
            }
            
            /deep/ .sfv-table_header-cell {
                height: 42px;
            }
            
            /deep/ .sfv-table_header {
                border: none;
            }
        }
        
        /deep/ .el-empty {
            height: calc(100% - 48px);
            
            .el-empty__image {
                .icon-comp-empty-status {
                    font-size: 50px;
                    color: #E0E0E0;
                }
            }
            
            .el-empty__description {
                font-size: 12px;
                line-height: 17px;
                color: #999999;
            }
        }
    }
}
</style>
